package util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 生成sql的工具类
 * 可用于条件查询或其他需动态拼接sql及参数的情况
 * 使用时需实例化
 */
public class SqlBuilder {
	private String prefixSql;//SQL前缀
	private String suffixSql;//SQL后缀
	private StringBuffer buffer;
	private List<Object> params;
	

	public void init() {
		buffer = new StringBuffer(this.prefixSql);
		params = new ArrayList<Object>();
	}
	
	public SqlBuilder(String prefixSql) {
		this.prefixSql = prefixSql;
		this.suffixSql = "";
		init();
	}
	
	public SqlBuilder(String prefixSql, String suffixSql) {
		this.prefixSql = prefixSql;
		this.suffixSql = suffixSql;
		init();
	}
	
	/**
	 * 初始化参数列表
	 * 用于多次拼接
	 * @param params
	 */
	public void initParams(Object[] params) {
		this.params = Arrays.asList(params);
	}
	
	/**
	 * 拼接字符串
	 * @param sql
	 */
	public void addSqlString(String str) {
		buffer.append(" " + str + " ");
	}
	
	/**
	 * 拼接条件
	 * @param isNecessary
	 * @param condition
	 * @param param
	 */
	public void addCondition(Boolean isNecessary, String condition, Object param) {
		if(isNecessary) {
			buffer.append(" and ( " + condition + " ) ");
			params.add(param);
		}
	}
	
	/**
	 * 返回拼接好的sql语句
	 * @return
	 */
	public String returnSql() {
		return buffer.append(" " + suffixSql + " ").toString();
	}
	
	/**
	 * 返回参数列表
	 * @return
	 */
	public Object[] returnParams() {
		Object[] array =  new String[ params.size()];
		return params.toArray(array);  
	}
	
}
